<template>
    <div>
        <TableBar
      :columns="columns"
      @changeColumn="changeColumn"
      :layout="layout"
      @closed="() => this.resetSearchInfo()"
    >
      <div slot="bottom">
        <el-row>
          <el-col :span="6">
            <el-button type="primary" plain size="mini" @click="dialog"
            v-auth="'processing_craft_insert'"
              >新增</el-button
            >
          </el-col>
          <el-col :span="12" v-if="!hiddenBtn">
            <el-select
              @change="(value) => this.processId = value"
              v-model="processId"
              placeholder="请选择加工厂"
              size="mini"
              v-auth="'processing_craft_insert'"
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <div slot="top">
        <el-form label-width="80px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="工艺名称">
                <el-input
                  placeholder="请输入工艺名称"
                  v-model="searchValue"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-row
              :xs="24"
              :sm="12"
              :lg="6"
              style="float: right; margin-right: 10px"
            >
              <el-button type="primary" @click="search" v-auth="'processing_craft_select'">搜索</el-button>
              <el-button
                @click="
                  () => {
                    this.searchValue = '';
                    this.setAllList();
                  }
                "
                v-auth="'processing_craft_select'"
                >重置</el-button
              >
            </el-row>
          </el-row>
        </el-form>
      </div>
    </TableBar>
    <!-- 表格区域 -->
    <TheTable
      :data="allList"
      :page.sync="page"
      :showPage="showPage"
      @changeSize="changeSize"
      @changePage="changePage"
      :Bottom="35"
    >
      <div
        v-for="item in columns"
        :key="item.id"
        class="item"
        effect="dark"
        placement="top-start"
      >
        <el-table-column
          :label="item.name"
          v-if="item.show"
          :prop="item.prop"
          show-overflow-tooltip
        ></el-table-column>
      </div>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            mini
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="dialog(scope.row)"
          ></el-button>
          <el-button
            mini
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delInfo(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </TheTable>
    <!-- 对话框区域 -->
    <el-dialog
      :title="dialogTitle"
      width="500px"
      :visible.sync="showDialog"
      top="20vh"
      @close="clearform"
    >
      <el-form
        label-position="right"
        ref="formRef"
        :rules="rules"
        :model="form"
        label-width="110px"
      >
        <el-form-item label="工艺名称" prop="name">
          <el-input v-model="form.name" placeholder="请填写工艺名称"></el-input>
        </el-form-item>
        <el-form-item label="工艺描述" prop="operation">
          <el-input
            type="textarea"
            placeholder="请输入工艺描述"
            v-model="form.operation"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="加工厂" prop="factoryId">
          <el-select
            @change="changeFactory"
            v-model="form.factoryId"
            placeholder="请选择加工厂"
            size="mini"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="clearform()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    </div>
</template>

<script>
import { mapState } from "vuex";
import {
  getAllInfoByPage,
  getInfoByName,
  addInfo,
  delInfoById,
  editInfo,
} from "../../../Api/processingplant/process_craft";
export default {
  name: "ProcessManagement",
  data() {
    return {
      allList: [],
      columns: [
        // 表头数据
        { name: "工艺编号", show: true, prop: "id" },
        { name: "工艺名称", show: true, prop: "name" },
        { name: "工艺操作描述", show: true, prop: "operation" },
        { name: "所属加工厂ID", show: true, prop: "factoryId" },
      ],
      layout: "search, refresh, column",
      form: {},
      rules: {
        name: [
          {
            required: true,
            message: `请输入工艺名称`,
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: `工艺名称的长度在2~10个字符之间`,
            trigger: "blur",
          },
        ],
        operation: [
          {
            required: true,
            message: `请输入工艺描述`,
            trigger: "blur",
          },
        ],
        factoryId: [
          {
            required: true,
            message: "请选择加工厂",
            trigger: "change",
          },
        ],
      },
      showDialog: false,
      showPage: true, // 显示分页
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      processId: "",
      hiddenBtn: false,
      dialogTitle: "新增",
      searchValue: "",
    };
  },
  computed: {
    ...mapState("process", {
      processList: (state) => state.processList,
      staffList: (state) => state.staffList,
    }),
    serachFlag() {
      return !!this.searchValue;
    },
  },
  watch: {
    // 加工厂变化的时候
    processId(processId) {
      this.setAllList();
    },
  },
  created() {
    console.log("this.processList: ", this.processList);
    // 如果没有加工厂，隐藏新增按钮
    if (this.processList.length !== 0) {
      this.processId = this.processList[0].id;
    } else {
      this.hiddenBtn = true;
    }
    // this.setAllList();
    console.log(this.processList);
  },
  methods: {
    // 重置分页信息
    ressetPageInfo() {
      this.page.current = 1
      this.page.pageSize = 10
    },
    // 关闭顶部搜索栏，重置搜索信息
    resetSearchInfo() {
      if (this.serachFlag) {
        this.searchValue = "";
        this.ressetPageInfo()
        this.setAllList();
      }
    },
    // 模糊查询加工厂信息
    async search() {
      if (this.searchValue != "") {
        const { data: res } = await getInfoByName(
          this.searchValue,
          this.page.current,
          this.page.pageSize
        );
        if (res.statusCode !== 20000) {
          return this.$message.error(res.message);
        }
        console.log(res);
        this.allList = res.data.records;
        this.page.total = res.data.total;
      } else return this.$message.info("请输入有效信息");
    },
    changeFactory(value) {
      this.form.factoryId = value;
      console.log(this.form);
    },
    // 获取数据
    async setAllList() {
      const { data: res } = await getAllInfoByPage(
        this.processId,
        this.page.current,
        this.page.pageSize
      );
      console.log(res);
      if (res.statusCode !== 20000) {
        return this.$message.error(res.message)
      }
      this.allList = res.data.records;
      this.page.total = res.data.total;
    },
    // 打开弹窗
    dialog(row = {}) {
      console.log("row: ", row);
      let form = JSON.parse(JSON.stringify(row));
      if (row.id) {
        // 修改
        this.form = form;
        this.dialogTitle = "修改";
      } else {
        // 增加
        console.log(11111111);
        this.dialogTitle = "新增";
        // this.form.factoryId = this.processId;
        this.$set(this.form, "factoryId", this.processId);
      }
      this.showDialog = true;
    },
    // 提交按钮
    async submit() {
      this.$refs.formRef.validate(async (val) => {
        if (!val) return false;
        if (!this.form.id) {
          // 增加
          const { data: res } = await addInfo(this.form);
          if (res.statusCode !== 20000) {
            return this.$message.error(res.message);
          } else {
            this.clearform();
            this.$message.success(res.message);
            this.setAllList();
          }
        } else {
          // 修改
          console.log(this.form);
          const { data: res } = await editInfo(this.form);
          console.log(res);
          if (res.statusCode !== 20000) {
            console.error(res.message);
            this.$message.error(res.message);
          } else {
            this.clearform();
            this.$message.success(res.message);
            this.setAllList();
          }
        }
      });
    },
    // 删除按钮
    async delInfo(id) {
      this.$confirm("此操作将永久删除该信息，请谨慎操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await delInfoById(id);
          console.log("res: ", res);
          if (res.statusCode !== 20000) {
           return this.$message.error(res.message);
          } else {
            this.ressetPageInfo()
            this.setAllList();
            this.$message.success(res.message);
          }
        })
        .catch(() => {
          return this.$message.info("已取消删除！");
        });
    },
    // 对话框关闭还原表单
    clearform() {
      this.$refs["formRef"].resetFields();
      this.showDialog = false;
    },
    // 选择显示隐藏列
    changeColumn(newcolumns) {
      this.columns = newcolumns;
    },
    // 分页 改变页码
    changePage(page) {
      this.page.current = page.current;
      console.log(this.serachFlag)
      if (this.serachFlag) this.search();
      else this.setAllList();
    },
    // 分页 改变每页显示的条数
    changeSize(size) {
      this.page.pageSize = size.pageSize;
      console.log(this.serachFlag)
      if (this.serachFlag) this.search();
      else this.setAllList();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form .el-form-item .el-input {
  width: 300px;
}
</style>